package com.yami.shop.consign.common.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.vo.ConsignRecordVO;
import com.yami.shop.bean.vo.ProdConfigVO;
import com.yami.shop.common.bean.PageDTO;
import com.yami.shop.common.bean.PageVO;
import com.yami.shop.common.util.PageUtil;
import com.yami.shop.common.util.StringAmountCalUtil;
import com.yami.shop.consign.common.dao.ConsignRecordMapper;
import com.yami.shop.consign.common.model.ConsignRecord;
import com.yami.shop.consign.common.service.ConsignRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class ConsignRecordServiceImpl extends ServiceImpl<ConsignRecordMapper, ConsignRecord> implements ConsignRecordService {

    @Autowired
    private ConsignRecordMapper consignRecordMapper;

    @Override
    public PageVO<ConsignRecordVO> getRecordList(PageDTO pageDTO, String nftId) {
        PageVO<ConsignRecordVO> pageVO = PageUtil.doPage(pageDTO, () -> consignRecordMapper.getRecordList(nftId));
        return pageVO;
    }

    @Override
    public void saveRecord(ConsignRecord consignRecord) {
        consignRecordMapper.insert(consignRecord);
    }

    @Override
    public ProdConfigVO getAvgLatestPriceByProdId(Integer prodId) {
        ProdConfigVO prodConfigVO = new ProdConfigVO();
        prodConfigVO.setProdId(prodId);
        String avgPrice = consignRecordMapper.getYesterdayAvgPrice(prodId);
        avgPrice = StringAmountCalUtil.FourUpSixIntoScale(avgPrice, 0);
        prodConfigVO.setAvgPrice(Integer.valueOf(avgPrice));
        ConsignRecord latestOne = getOne(new LambdaQueryWrapper<ConsignRecord>()
                .eq(ConsignRecord::getProdId, prodId).eq(ConsignRecord::getType, 1).orderByDesc(ConsignRecord::getCreateTime).orderByDesc(ConsignRecord::getId).last("limit 1"));
        if (Objects.nonNull(latestOne)) {
            prodConfigVO.setLatestPrice(latestOne.getPrice().intValue());
            prodConfigVO.setLatestTime(latestOne.getCreateTime());
        }
        return prodConfigVO;
    }

    /**
     * 寄售买入记录
     * @param consignRecordVO
     * @return
     */
    @Override
    public Long saveRecordVo(ConsignRecordVO consignRecordVO) {
        ConsignRecord record = BeanUtil.copyProperties(consignRecordVO, ConsignRecord.class);
        consignRecordMapper.insert(record);
        return record.getId();
    }


}
